<template>
  <div class="add-pay-container">
    <div class="expense-add">
      <!-- 顶部导航区域 -->
      <div class="header-wrapper">
        <!-- 顶部导航 -->
        <div class="header">
          <van-icon name="arrow-left" class="back-icon" @click="goBack" />
          <div class="header-title">付款申请</div>
        </div>
      </div>
      <!-- 表单内容 -->
      <div class="form-container">
             <!-- 付款备注 -->
        <div class="form-field textarea-field">
          <div class="field-label">付款事由</div>
          <van-field
            v-model="payFormStore.formData.payRemark"
            placeholder="请输入付款事由"
            type="textarea"
            rows="3"
            :border="false"
            class="custom-field"
            maxlength="2000"
            show-word-limit
            autocomplete="off"
          />
        </div>
        <!-- form表单金额 -->
        <div class="form-field">
          <div class="field-label">付款总额</div>
          <van-field
            v-model="payFormStore.formData.payAmount"
            placeholder="请输入"
            type="number"
            :border="false"
            class="custom-field"
            autocomplete="off"
          />
        </div>
            <!-- 新增：付款凭证上传，保持与报销上传一致 -->
        <div class="form-field form-contract-uploader" @click="openPayUploaderInput($event)">
          <div class="field-label ">付款凭证</div>
          <VantUploader ref="payUploaderCompRef" v-model="fileList" :max-file-count="5" :max-file-size-m-b="10" />
        </div>
        <!-- 付款日期 -->
        <div class="form-field">
          <div class="field-label">付款日期</div>
          <van-field
            v-model="payFormStore.formData.payDate"
            is-link
            readonly
            placeholder="请选择"
            @click="payFormStore.showPayDatePicker = true"
            :border="false"
            class="custom-field"
            autocomplete="off"
          />
        </div>
        <!-- 付款对象 -->
        <div class="form-field">
          <div class="field-label">付款对象</div>
            <van-field
            v-model="payFormStore.formData.payObjectText"
            placeholder="请选择付款对象"
            :border="false"
            class="custom-field"
            autocomplete="off"
            is-link
            readonly
            @click="selectPayObject"
          />

        </div>

        <!-- 流程步骤 -->
        <div class="form-container">
          <div class="process-step-container">
            <div class="process-step-title">流程</div>
            <div class="process-steps">
              <div
                v-for="(step, index) in payFormStore.approvalSteps"
                :key="index"
                class="process-step"
                :class="{ 'is-last': index === payFormStore.approvalSteps.length - 1 }"
              >
                <!-- 左侧步骤条 -->
                <div class="step-line-container">
                  <div class="step-dot"></div>
                  <div
                    v-if="index < payFormStore.approvalSteps.length - 1"
                    class="step-line"
                  ></div>
                </div>

                <!-- 右侧人员信息 -->
                <div class="step-info">
                  <div class="step-title-container">
                    <div class="step-title">{{ step.title }}</div>
                    <div v-if="step.subtitle" class="step-subtitle">
                      {{ step.subtitle }}
                    </div>
                  </div>
                  <div class="step-person">
                    <div class="person-avatar">
                      <AvatarDisplay :url="step.url" :name="step.name" />
                    </div>
                    <div class="person-name">{{ step.name }}</div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 底部操作按钮 -->
        <div class="action-buttons">
          <van-button 
            class="action-btn submit-btn" 
            :disabled="payFormStore.submitting" 
            :loading="payFormStore.submitting && payFormStore.approvalSteps.length > 0"
            @click="submitPay"
          >
            提交
          </van-button>
        </div>
      </div>
    </div>

    <!-- 付款对象选择 -->
    <van-action-sheet
      v-model:show="payFormStore.showPayObjectSheet"
      :actions="payObjectActions"
      title="选择付款对象"
      @select="onPayObjectSelect"
      cancel-text="取消"
    />

    <!-- 付款日期选择器 -->
    <van-popup v-model:show="payFormStore.showPayDatePicker" position="bottom">
      <van-date-picker
        v-model="payFormStore.payDateArray"
        title="选择付款日期"
        @confirm="onPayDateConfirm"
        @cancel="payFormStore.showPayDatePicker = false"
      />
    </van-popup>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onActivated, watch } from "vue";
import { useRouter, useRoute, onBeforeRouteLeave } from "vue-router";
import { showToast } from "vant";
import { addPay } from "@/api/contract";
import { queryFlow, getUserPicture } from "@/api/contract";
import pictureImg from "@/assets/homeOther/picture.png";
import AvatarDisplay from '@/components/UserAvatar/AvatarDisplay.vue';
import { navigateAfterSubmit, smartGoBack } from '@/utils/navigation';
import { usePayFormStore } from '@/stores/payForm';
import VantUploader from '@/components/UploadFiled/VantUploader.vue';
import { storage } from '@/utils/storage';
import { openUploadFromRowClick } from '@/utils/uploadTrigger';
import { useHardwareBackCleanup } from '@/utils/hardwareBackCleanup';
defineOptions({ name: 'ContractAddPay' })

const router = useRouter();

// 让整行（含标签）都能触发上传：点击时主动触发内部 input[type=file]
const payUploaderCompRef = ref(null);
  const openPayUploaderInput = (e) => {
    openUploadFromRowClick(e, payUploaderCompRef.value);
  };
const route = useRoute();
const payFormStore = usePayFormStore();

// 重置新增付款页状态
const resetPayAddState = () => {
  // 清空 Pinia 表单
  payFormStore.resetForm();
  // 清空附件
  fileList.value = [];
  uploadedFiles.value = '';
};

// 绑定手机系统返回（popstate）时的清理逻辑
useHardwareBackCleanup('ContractAddPay', resetPayAddState);

// 返回上一页
const goBack = () => {
  // 先重置本地与 Pinia 状态
  resetPayAddState();
  // 再清理 KeepAlive 缓存
  window.dispatchEvent(new CustomEvent('clear-keepalive-cache', { detail: { name: 'ContractAddPay' } }));
  smartGoBack(router);
};

// 使用 Vant Uploader 的文件列表（与报销上传保持一致）
const fileList = ref([]);
// 统一的附件字符串（以逗号拼接的服务器路径）
const uploadedFiles = ref("");

// 从 store 中的 attachmentUrl 恢复 fileList（仅在初始化时执行一次）
const initializeFilesFromStore = () => {
  const attachmentUrl = payFormStore.formData.attachmentUrl;
  if (attachmentUrl && attachmentUrl.trim() !== '' && fileList.value.length === 0) {
    const paths = attachmentUrl.split(',').filter(Boolean);
    fileList.value = paths.map((path, index) => {
      // 创建完整的文件对象结构，确保所有必要属性都存在
      const fileObj = {
        id: `file-${index}`,
        serverPath: path,
        name: `附件${index + 1}`,
        url: path,
        status: 'done',
        file: null, // 明确设置为null，避免undefined
        isImage: false, // 默认值，后续会通过ensureIsImage更新
        uploadedPath: path, // 添加uploadedPath属性
        message: '已上传' // 添加状态消息
      };
      return fileObj;
    });
    uploadedFiles.value = attachmentUrl;
  }
};

// 同步 fileList 到附件字符串，并保存到 store
watch(
  fileList,
  (list) => {
    const paths = (list || [])
      .map((f) => f.serverPath)
      .filter(Boolean)
      .join(',');
    uploadedFiles.value = paths;
    // 将附件字符串保存到 store，保持与报销提交参数一致
    payFormStore.saveFormData({ attachmentUrl: uploadedFiles.value });
  },
  { deep: true }
);

// 跳转到组织架构选择付款对象
const selectPayObject = () => {
  // 跳转前保存当前表单数据到store
  payFormStore.saveFormData({
    payAmount: payFormStore.formData.payAmount,
    payDate: payFormStore.formData.payDate,
    payObject: payFormStore.formData.payObject,
    payObjectText: payFormStore.formData.payObjectText,
    payRemark: payFormStore.formData.payRemark,
    // 新增：保存附件字符串，避免页面跳转丢失
    attachmentUrl: uploadedFiles.value
  });
  
  router.push({
    path: '/organization',
    query: {
      mode: 'select', // 标记为选择模式
      from: 'payObject' // 标记来源为付款对象
    }
  });
};

// 使用store中的状态 - 直接引用保持响应式
// 注意：不能使用解构赋值，会破坏响应式连接

// 获取姓名后两位字符作为头像
const getNameInitials = (name) => {
  if (!name) return '';
  return name.length >= 2 ? name.slice(-2) : name;
};

// 获取当前日期数组格式
const getCurrentDateArray = () => {
  const now = new Date();
  const year = now.getFullYear().toString();
  const month = (now.getMonth() + 1).toString().padStart(2, '0');
  const day = now.getDate().toString().padStart(2, '0');
  return [year, month, day];
};

// 选择器显示状态和日期数组已在store中定义

// 付款对象选项
const payObjectActions = [
  { name: "供应商A", value: "1" },
  { name: "供应商B", value: "2" },
  { name: "供应商C", value: "3" },
  { name: "其他", value: "4" }
];

// 显示付款对象选择器
const showPayObjectSelector = () => {
  payFormStore.showPayObjectSheet = true;
};

// 付款对象选择
const onPayObjectSelect = (action) => {
  payFormStore.updateField('payObject', action.value);
  payFormStore.updateField('payObjectText', action.name);
  payFormStore.showPayObjectSheet = false;
};

// 付款日期确认
const onPayDateConfirm = ({ selectedValues }) => {
  const [year, month, day] = selectedValues;
  const dateStr = `${year}-${month.toString().padStart(2, "0")}-${day
    .toString()
    .padStart(2, "0")}`;
  payFormStore.updateField('payDate', dateStr);
  payFormStore.showPayDatePicker = false;
};

// 加载用户头像
const loadUserAvatar = async (url) => {
  if (!url) return 'text'; // 返回标识符表示使用文字头像
  
  try {
    const blob = await getUserPicture(url);
    return URL.createObjectURL(blob);
  } catch (error) {
    console.error('加载头像失败:', error);
    return 'text'; // 加载失败时使用文字头像
  }
};

// 查询流程信息
const loadFlowData = async () => {
  try {
    const response = await queryFlow();
    
    if (response.code === 0 && response.data) {
      const { firstApprover, secondApprover, thirdApprover } = response.data;
      
      // 收集所有有效的审批人
      const approvers = [];
      
      if (firstApprover && Object.keys(firstApprover).length > 0) {
        approvers.push(firstApprover);
      }
      
      if (secondApprover && Object.keys(secondApprover).length > 0) {
        approvers.push(secondApprover);
      }
      
      if (thirdApprover && Object.keys(thirdApprover).length > 0) {
        approvers.push(thirdApprover);
      }
      
      // 检查是否有审批人
      if (approvers.length === 0 || approvers.length === 1) {
        // Toast提示并禁用提交按钮
        showToast('该公司尚未设置CEO或组织架构尚未完善');
        payFormStore.setSubmitting(true); // 禁用提交按钮
        return;
      }
      
      // 动态构建审批步骤数组，级别从1开始
      const steps = [];
      
      for (let i = 0; i < approvers.length; i++) {
        const approver = approvers[i];
        const avatar = await loadUserAvatar(approver.url);
        steps.push({
          title: "审批人",
          subtitle: `${i + 1}级审批`,
          name: approver.name,
          avatar: avatar,
          url: approver.url,
          id: approver.id
        });
      }
      
      // 更新审批步骤
      payFormStore.setApprovalSteps(steps);
    }
  } catch (error) {
    console.error('查询流程失败:', error);
    showToast('加载流程信息失败');
  }
};

// 提交付款申请
const submitPay = async () => {
  // 表单验证 - 必填项校验
  if (!payFormStore.formData.payAmount || payFormStore.formData.payAmount <= 0) {
    showToast("请输入有效的付款金额");
    return;
  }
  if (!payFormStore.formData.payDate) {
    showToast("请选择付款日期");
    return;
  }
  if (!payFormStore.formData.payObjectText || payFormStore.formData.payObjectText.trim() === '') {
    showToast("请输入付款对象");
    return;
  }
  if (!payFormStore.formData.payRemark || payFormStore.formData.payRemark.trim() === '') {
    showToast("请输入付款事由");
    return;
  }
  // 新增：校验是否上传了付款凭证
  if (!uploadedFiles.value || uploadedFiles.value === '') {
    showToast('请上传付款凭证');
    return;
  }

  try {
    payFormStore.setSubmitting(true);

    // 构建API请求参数
    const requestData = {
      payRemark: payFormStore.formData.payRemark.trim(), // 付款事由
      payAmount: parseFloat(payFormStore.formData.payAmount), // 付款金额
      payDate: payFormStore.formData.payDate, // 付款日期
      payObject: payFormStore.formData.payObject || payFormStore.formData.payObjectText.trim(), // 付款对象（优先使用用户ID，否则使用文本）
      // 新增：附件参数，保持与报销一致
      attachmentUrl: uploadedFiles.value
    };

    // 调用付款申请接口
    const response = await addPay(requestData);
    
    if (response.code === 0) {
      showToast({ type: 'success', message: response.msg || "申请付款流程成功" });
      
      // 提交成功后先重置本地与 Pinia 状态
      resetPayAddState();
      
      // 清理本页缓存，确保下次进入为空白
      window.dispatchEvent(new CustomEvent('clear-keepalive-cache', { detail: { name: 'ContractAddPay' } }));
      
      // 使用统一的导航工具函数处理跳转
      navigateAfterSubmit(router, response);
    } else {
      showToast(response.msg || "提交失败，请重试");
    }
  } catch (error) {
    console.error('提交付款申请失败:', error);
    showToast("提交失败，请重试");
  } finally {
    payFormStore.setSubmitting(false);
  }
};

// 处理从组织架构页面返回的选择结果
const handleSelectedUser = () => {
  const selectedUserId = route.query.selectedUserId;
  const selectedUserName = route.query.selectedUserName;
  
  if (selectedUserId && selectedUserName) {
    // 回填选择的用户信息
    payFormStore.updateField('payObject', selectedUserId);
    payFormStore.updateField('payObjectText', selectedUserName);
    
    // 清除URL中的查询参数，避免重复处理
    router.replace({ path: route.path });
    return;
  }
  
  // 兜底：若组织页通过 storage 返回
  const cached = storage.getItem('selectedPayObject');
  if (cached) {
    try {
      const { id, name } = JSON.parse(cached);
      payFormStore.updateField('payObject', id || '');
      payFormStore.updateField('payObjectText', name || '');
    } catch (error) {
      console.error('解析 selectedPayObject 失败:', error);
    }
    storage.removeItem('selectedPayObject');
  }
};

// 组件挂载时初始化数据
onMounted(() => {
  // 初始化日期数组
  payFormStore.initializeDateArray();
  
  // 加载流程数据
  loadFlowData();
  
  // 处理从组织架构页面返回的选择结果
  handleSelectedUser();
  
  // 从 store 恢复附件列表（仅初始化时执行一次）
  initializeFilesFromStore();
});

// 从其它页面返回（组织架构 / 预览）
onActivated(() => {
  // 处理从组织架构页面返回的选择结果
  handleSelectedUser();
});

// 页面离开时的统一清理：
// - 前往附件预览（/file-preview*）或组织架构（/organization*）时保留数据；
// - 其它任何离开（包括系统返回/左滑、跳转详情等）一律清理，确保各端一致。
onBeforeRouteLeave((to) => {
  try {
    const destPath = to?.path || '';
    const goingToPreview = destPath.startsWith('/file-preview');
    const goingToOrganization = destPath.startsWith('/organization');

    if (goingToPreview || goingToOrganization) {
      return; // 不清理，保持表单与附件
    }

    resetPayAddState();
    window.dispatchEvent(new CustomEvent('clear-keepalive-cache', { detail: { name: 'ContractAddPay' } }));
  } catch (err) {
    console.warn('[ContractAddPay] onBeforeRouteLeave cleanup failed:', err);
  }
});



// 监听表单数据变化，实时保存到store（新增附件字段）
watch(
  () => [
    payFormStore.formData.payAmount,
    payFormStore.formData.payDate,
    payFormStore.formData.payObject,
    payFormStore.formData.payObjectText,
    payFormStore.formData.payRemark,
    uploadedFiles.value
  ],
  () => {
    // 实时保存表单数据变化
    payFormStore.saveFormData({
      payAmount: payFormStore.formData.payAmount,
      payDate: payFormStore.formData.payDate,
      payObject: payFormStore.formData.payObject,
      payObjectText: payFormStore.formData.payObjectText,
      payRemark: payFormStore.formData.payRemark,
      // 新增：附件字符串
      attachmentUrl: uploadedFiles.value
    });
  },
  { deep: true }
);

// 页面离开时保存数据（新增附件字段）
const saveDataBeforeLeave = () => {
  payFormStore.saveFormData({
    payAmount: payFormStore.formData.payAmount,
    payDate: payFormStore.formData.payDate,
    payObject: payFormStore.formData.payObject,
    payObjectText: payFormStore.formData.payObjectText,
    payRemark: payFormStore.formData.payRemark,
    // 新增：附件字符串
    attachmentUrl: uploadedFiles.value
  });
};

// 监听路由变化，在离开页面前保存数据
watch(
  () => route.path,
  (newPath, oldPath) => {
    if (oldPath === '/contract/addPay' && newPath !== '/contract/addPay') {
      saveDataBeforeLeave();
    }
  }
);
</script>

<style lang="scss" scoped>
@import url("./style/addPay.scss");
</style>